package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Slf4j
@Configuration
public class SearcherConfig {

    @Value("${ip2region.address}")
    private String path;

    @Bean("searcher")
    public Searcher getSearcher() {
        String xdbPath;
        if (StringUtils.isNotBlank(this.path)) {
            xdbPath = this.path;
        } else {
            xdbPath = Objects.requireNonNull(this.getClass().getResource("/ip-address/ip2region.xdb")).getPath();
        }

        log.info("path: {}", xdbPath);

        // 1、从 path 加载整个 xdb 到内存。
        byte[] cBuff = new byte[0];
        try {
            cBuff = Searcher.loadContentFromFile(xdbPath);
        } catch (Exception e) {
            log.error("failed to load content from {}: {}", xdbPath, e);
            e.printStackTrace();
        }

        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        try {
            return Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            log.error("failed to create content cached searcher");
            e.printStackTrace();
        }

        return null;
    }
}
